<?php
namespace Api\Controller;

use EasyWeChat\Foundation\Application;

class WeChatController extends  BaseController {

    public $config = [
        'debug'         => true,
        'app_id'        => 'wx3ca3d21cc7809a21',
        'secret'        => '77dc7140d3ef7717b893504c60aa387f',
        'token'         => '',
        'aes_key'       => '',
        // 'mch_id'        => '',
        // 'mch_pay_key'   => '',
        // 'mch_cert'      => '',
        // 'mch_cert_key'  => '',
    ];

    public function _initialize(){
        parent::_initialize();

        require_once VENDOR_PATH.'autoload.php';
        // $this->weixin = $weixin;
        
    }

    public function __construct($config = []){
        parent::__construct();
        // if(in_array(ACTION_NAME, ['auth', 'auth_back'])){
            $config['app_id'] = 'wx06900aa14b6ded59';
            $config['secret'] = '0f0cc2a62b36823f18213624336d7802';
        // }
        $config = array_merge($this->config, $config);

        $options = [
            /**
             * Debug 模式，bool 值：true/false
             *
             * 当值为 false 时，所有的日志都不会记录
             */
            'debug'  => true,

            /**
             * 账号基本信息，请从微信公众平台/开放平台获取
             */
            'app_id'  => $config['app_id'],        // AppID
            'secret'  => $config['secret'],   // AppSecre
            'token'   => $config['token'],        // Token
            'aes_key' => null,          // 可选 EncodingAESKey，安全模式下请一定要填写！！！

            /**
             * 日志配置
             *
             * level: 日志级别, 可选为：
             *         debug/info/notice/warning/error/critical/alert/emergency
             * permission：日志文件权限(可选)，默认为null（若为null值,monolog会取0644）
             * file：日志文件位置(绝对路径!!!)，要求可写权限
             */
            'log' => [
                'level'         => 'debug',
                'permission'    => 0777,
                'file'          => LOG_PATH.'easywechat.log', // XXX: 绝对路径！！！！
            ],

            /**
             * OAuth 配置
             *
             * scopes：公众平台（snsapi_userinfo / snsapi_base），开放平台：snsapi_login
             * callback：OAuth授权完成后的回调页地址
             */
            // 'oauth' => [
            //     'scopes'   => ['snsapi_userinfo'],
            //     'callback' => U('auth_back', [], true, true),
            // ],

            /**
             * 微信支付
             */
            // 'payment' => [
            //     'merchant_id'        => $weixin['mch_id'],        // 商户号id
            //     'key'                => $weixin['mch_pay_key'],   // 支付密钥
            //     'cert_path'          => $weixin['mch_cert'],      // 证书: 绝对路径！！！！ 
            //     'key_path'           => $weixin['mch_cert_key'],  // 证书密钥: 绝对路径！！！！
            // ],

            /**
             * 小程序
             */
            // 'mini_program' => [
            //     'app_id'   => 'component-app-id',
            //     'secret'   => 'component-app-secret',
            //     'token'    => 'component-token',
            //     'aes_key'  => 'component-aes-key'
            // ],
            // ...
        ];
        $this->app_id = $options['app_id'];
        try {
            $this->app = new Application($options);
        } catch (\Exception $e) {
            // trace('初始化失败：' . $e->getMessage());
        }        
    }

    /**
     * 生成js配置
     * @param  array   $APIs  JS接口列表
     * @param  boolean $debug 是否开启调试模式
     * @param  string  $url   生成签名的网页URL
     * @return json
     */
    public function js_config($APIs, $debug = false, $url = ''){
        $js = $this->app->js;
        if($url){
            $js->setUrl($url);
        }
        $res = $js->config($APIs,  $debug, $beta = false, $json = false);
        return $res;
    }

    // 微信授权
    public function auth()
    {
        $callback = isset($_GET['callback']) ? $_GET['callback'] : '';
        try {
            $wxmopenid = cookie('wxmopenid');
            if($wxmopenid = json_decode($wxmopenid, true)){
                $this->jump(['openid'=>$wxmopenid]);
            }
            $oauth = $this->app->oauth;
            if($callback){
                $oauth->setRedirectUrl(U('auth_back', [], true, true).'?callback='.$callback);
                // $oauth->setRedirectUrl($callback);
            }
            $response = $oauth->scopes(['snsapi_userinfo'])->redirect();
            $response->send();
        } catch (\Exception $e) {
            exit($e->getMessage());
        }
        die;
    }

    /**
     * 下载临时素材到本地
     * @param  string $media_id 媒体ID
     * @return array
     */
    public function download()
    {
        $media_id = I('media_id');
        try {
            // 临时素材
            $temporary = $this->app->material_temporary;
            list($response, $content) = $temporary->getResponse($media_id);
            $mime = $response->getHeader('Content-Type');
            $mime = is_array($mime) ? $mime[0] : '';
            // 临时文件
            $file_name = 'php'.date('YmdHis').rand(10000, 99999);
            $tmp_name = sys_get_temp_dir().'/'.$file_name.($extension ? '.'.$extension : '');
            file_put_contents($tmp_name, $content);
            $mimes = getMimes();
            $extension = array_search($mime, $mimes);
            $file = [];
            $file['name'] = $media_id.($extension ? '.'.$extension : '');
            $file['type'] = $mime;
            $file['size'] = filesize($tmp_name);
            $file['tmp_name'] = $tmp_name;
            $upload = new \Think\Upload();// 实例化上传类
            $upload->maxSize   = 5242880;// 设置附件上传大小
            $upload->exts      = array($extension);// 设置附件上传类型
            $upload->rootPath  = './'.C('UPLOAD_PATH').'/files/'; // 设置附件上传根目录
            $upload->savePath  = ''; // 设置附件上传（子）目录
            // 上传文件 
            $info   =   $upload->isTest(true)->upload([$file]);
            if(!$info) {// 上传错误提示错误信息
                $this->ajaxReturn(array('s' => false, 'm'=>$upload->getError()));
            }
            $info = $info[0];
            $info['path'] = C("SiteUrl").C('UPLOAD_PATH').'/files/'.$info['savepath'].$info['savename'];
            $this->ajaxReturn(array('s' => true, 'm'=>'ok', 'info'=>$info));
        } catch (\Exception $e) {
            $this->ajaxReturn(array('s' => false, 'm'=>$e->getMessage()));
        }
    }

    // 授权回调
    public function auth_back()
    {
        $code = I('code');
        if (empty($code)) {
            $this->error('code 参数缺少');
        }
        try {
            $oauth = $this->app->oauth;
            // 获取 OAuth 授权结果用户信息
            $user = $oauth->user();
            $wechat_user = $user->toArray();
            $original = $wechat_user['original'];// 原始API返回的结果
            cookie('wxmopenid', $original['openid'], 86400*7);
            $this->jump($original);
        } catch (\Exception $e) {
            exit($e->getMessage());
        }
    }

    public function jump($original)
    {
        $callback = isset($_GET['callback']) ? $_GET['callback'] : '';
        $storage = [];
        if($original['openid']){
            $user = M('user')->where(['wxmopenid'=>$original['openid']])->find();
            if(!empty($user)){
                $storage = [
                    'token'     => $user['cid'],
                    'hxUser'    => $user['phone'],// 环信账号
                    'hxPass'    => $user['phone'],// 环信密码
                    'mesList'   => [],
                ];
            }
        }
        if($callback){
            $querys = [
                'waback'    => '1',
                'wxuser'    => base64_encode(json_encode($original)),
                'storage'   => base64_encode(json_encode($storage)),
            ];
            // $url = $callback.(strrpos($callback, "?") ? '&':'?') . http_build_query($querys);
            $url = $callback.(strrpos($callback, "?") ? '&':'?') . "waback=1&wxuser=".base64_encode(json_encode($original)).'&storage='.base64_encode(json_encode($storage));
            header("Location: {$url}");
        }
        exit();
    }
}